<template>
  {{status}}
  <el-button @click="InitSocket">重新连接</el-button>
  <el-button @click="CloseSocket">断开链接</el-button>
  <el-input v-model="value"></el-input><el-button @click="Send">发送</el-button>

  <div id="message">
    <ul >
      <template v-for="(item,idex) in messages">
        <li>{{item.msg}}</li>
      </template>
    </ul>
  </div>
</template>

<script setup>
import {ref,onBeforeUnmount,reactive,onMounted,watch} from 'vue'
import { ElLoading } from 'element-plus'
const value = ref(null)
const message = ref("null")
const status = ref(false)
let socket = reactive(null)
const loading = ref(true)
const messages = ref([])
watch(status, async (newQuestion, oldQuestion) => {
  openFullScreen2()
})

onMounted(()=>{
  InitSocket()
})

const InitSocket = ()=>{
  socket = new WebSocket('ws://localhost:8090/echo'); // 替换为你的 WebSocket 服务器地址和token
  socket.onopen = () => {
    console.log('WebSocket 连接已建立');
    messages.value = []
    status.value = true
    // 在连接建立后，可以发送消息或执行其他操作
  }

  socket.onmessage = (event) => {
    console.log('收到消息:', event.data);
    message.value = event.data
    messages.value.push(JSON.parse(event.data))
    // 处理收到的消息数据
  };

  socket.onclose = () => {
    console.log('WebSocket 连接已关闭');
    status.value = false
    messages.value = []
  }

}
const openFullScreen2 = () => {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  setTimeout(() => {
    loading.close()
  }, 2000)
}

const CloseSocket = ()=>{
  socket.close()
}


const Send = ()=>{
  socket.send(value.value)
}

onBeforeUnmount(()=>{
  if (socket) {
    socket.close(); // 在组件销毁前关闭 WebSocket 连接
  }
})
</script>

<style scoped>
#message {
  height: 60vh;
  overflow: auto;
}

li {
    font-size:12px;
    color:green;
}
</style>